package com.xayq.orap.oauth.token;


import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.xayq.orap.model.AccessToken;
import com.xayq.orap.utils.CommonUtils;

@Component
public class RefreshTokenHandler extends AbstractOAuthTokenHandler {

    private static final Logger LOG = LoggerFactory.getLogger(RefreshTokenHandler.class);


    /**
     * URL demo:
     * /oauth/token?client_id=mobile-client&client_secret=mobile&grant_type=refresh_token&refresh_token=b36f4978-a172-4aa8-af89-60f58abe3ba1
     *
     * @throws org.apache.oltu.oauth2.common.exception.OAuthProblemException
     */
    @Override
    public void handleAfterValidation() throws OAuthProblemException, OAuthSystemException {

        String refreshToken = tokenRequest.getRefreshToken();
        AccessToken accessToken = oAuthService.changeAccessTokenByRefreshToken(refreshToken, tokenRequest.getClientId());

        OAuthResponse tokenResponse = createTokenResponse(accessToken, false);

        LOG.debug("'refresh_token' response: {}", tokenResponse);
        CommonUtils.writeOAuthJsonResponse(response, tokenResponse);

    }


	@Override
	protected OAuthResponse validatePlus() throws OAuthSystemException {
		// TODO Auto-generated method stub
		String refreshToken = tokenRequest.getRefreshToken();
        AccessToken accessToken = oAuthService.loadAccessTokenByRefreshToken(refreshToken, tokenRequest.getClientId());
        if (accessToken == null || accessToken.refreshTokenExpired()) {
            LOG.debug("Invalid refresh_token: '{}'", refreshToken);
            return invalidRefreshTokenResponse(refreshToken);
        }

		return null;
	}
	
	private OAuthResponse invalidRefreshTokenResponse(String refreshToken) throws OAuthSystemException {
        return OAuthResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                .setError(OAuthError.TokenResponse.INVALID_GRANT)
                .setErrorDescription("Invalid refresh_token: " + refreshToken)
                .buildJSONMessage();
    }

}
